package com.youyiwen.Interception;

import com.youyiwen.Bean.Notice;
import com.youyiwen.Bean.User;
import com.youyiwen.Mapper.NoticeMapper;
import com.youyiwen.Mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: zhaoyang
 * @Date: 2021/03/22
 */
@Service
public class UserIntercepter implements HandlerInterceptor {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private NoticeMapper noticeMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        String psw1 = "1";
        String psw2 = "2";
        User user = null;
        String userName = null;

        if (cookies == null) {
            return true;
        }
        for (Cookie cookie : cookies) {
            if ("name".equals(cookie.getName())) {
                userName = cookie.getValue();
                psw1 = userMapper.searchPasswordByName(cookie.getValue());
                user = userMapper.selectUserByName(userName);
            }
            if ("password".equals(cookie.getName())) {
                psw2 = cookie.getValue();
            }
        }
        if (psw1.equals(psw2)) {
            request.getSession().setAttribute("loginUser", user);
            Integer count = noticeMapper.selectMsgCount(userName);
            request.getSession().setAttribute("msgCount",count);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
